package com.dyh.quickdemo.demos.spy;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

/*
@Author=Joey Wheeler
@Date=2020/12/4 11:26
*/
@Slf4j
public class SpyContextFacade {
   private static ThreadLocal<SpyContext> tl = ThreadLocal.withInitial(SpyContext::new);

    public static void add(Spy spy){
       // if (CollectionUtils.isEmpty(tl.get().getSpyChain()))
        //    tl.get().add(spy);
        tl.get().spyTimer.putIfAbsent(spy.methodName,System.currentTimeMillis());
        tl.get().stack.push(spy);
    }

//    public static List<Spy> spyChain(){
//        return tl.get().getSpyChain();
//    }

    public static void clean(){
        tl.remove();
    }

    public static void report(){
        if ( tl.get().stack==null)
            return;

        Spy spy = tl.get().stack.pop();
        long now = System.currentTimeMillis();
        long timeDiff = now-tl.get().spyTimer.get(spy.methodName);
        tl.get().getPrintChain().add(0,spy.fullInfo+"耗时:"+timeDiff+" ms");
        if (tl.get().stack.empty()){
            //log.info(JSON.toJSONString(tl.get().printChain));

            StringBuffer sb = new StringBuffer();
            sb.append("【spy report】");
            for (int i = 0;i<tl.get().printChain.size();i++){
                if (i==0)
                    sb.append("\n【start】\n↓\n");


                sb.append(tl.get().printChain.get(i)).append("\n↓\n");
                if (i==tl.get().printChain.size()-1)
                    sb.append("【end】");
            }
            log.info(sb.toString());
        }
//        if (tl.get().stack.size()==1){
//            tl.get().report.append("【end】");
//            log.info(tl.get().report.toString());
//        }
        //log.info(spy.fullInfo);
//        LinkedList<Spy> spyChain = tl.get().getSpyChain();
//        if (CollectionUtils.isEmpty(spyChain))
//            return;
//        StringBuffer sb = new StringBuffer();
//        for (int i = 0;i<spyChain.size();i++){
//            if (i==0)
//                sb.append("\n【start】\n↓\n");
//            sb.append(spyChain.get(i).fullInfo).append("\n↓\n");
//            if (i==spyChain.size()-1)
//                sb.append("【end】");
//        }
//        log.info("spy report:{}",sb);
    }

}
